package com.jinzhi.jzweb.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.domain.Tree;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.certificate.pojo.NoDisStuListVo;
import com.jinzhi.jzapi.msg.PackTemplateMap;
import com.jinzhi.jzapi.msg.WxPushServiceQcl;
import com.jinzhi.jzapi.msg.domain.TemplateData;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.pojo.StuSignUpVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.FileUtil;
import com.jinzhi.jzweb.utils.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxmp.domain.MpConfigDO;
import com.jinzhi.wxmp.service.MpConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <pre>
 * 考生报名
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Slf4j
@Controller
@RequestMapping("/jzweb/stuSignUp")
public class StuSignUpController extends BaseController {
	@Autowired
	private StuSignUpService stuSignUpService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private ExaminationRoomService examinationRoomService;
	@Autowired
	private DictService dictService;
	@Autowired
	private CertificationBatchService certificationBatchService;
	@Autowired
	private CertificateNewsService certificateNewsService;
	@Autowired
	private ExaminationPointService examinationPointService;
	@Autowired
	private ExaminationAllocationService examinationAllocationService;
	@Autowired
	private ExaminationBatchService examinationBatchService;
	@Autowired
	private OrganizationRolesService organizationRolesService;
	@Autowired
	private OrganizationNewsService organizationNewsService;
	@Autowired
	private TestPaperTemplateService testPaperTemplateService;
	@Autowired
	private MsgService msgService;
	@Autowired
	private MsgTemplateService msgTemplateService;
	@Autowired
	private WxPushServiceQcl wxPushServiceQcl;
	@Autowired
	private MpConfigService mpConfigService;
	@Autowired
	private ExaminationAnswerSheetService examinationAnswerSheetService;

	@GetMapping()
	@RequiresPermissions("jzweb:stuSignUp:stuSignUp")
	String StuSignUp(Model model) {
		//查询用户角色
		String roleName = getRoleNames();
		if (roleName.contains("超级用户角色")) {
			model.addAttribute("admin", "admin");
		}
		return "jzweb/stuSignUp/stuSignUp";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:stuSignUp:stuSignUp")
	public Result<Page<StuSignUpDO>> list(HttpServletRequest req, StuSignUpDO stuSignUpDTO) {
		Wrapper<StuSignUpDO> wrapper = new EntityWrapper<StuSignUpDO>().orderBy("id", false);
		if (stuSignUpDTO.getState() != null) {
			wrapper.eq("state", stuSignUpDTO.getState());
		}
		if (stuSignUpDTO.getName() != null) {
			wrapper.like("name", stuSignUpDTO.getName());
		}
		if (stuSignUpDTO.getType() != null) {
			wrapper.eq("type", stuSignUpDTO.getType());
		}
		if (org.apache.commons.lang3.StringUtils.isNotBlank(stuSignUpDTO.getCbatchName())) {
			Wrapper<ExaminationBatchDO> cbatWrapper = new EntityWrapper<ExaminationBatchDO>().like("name", stuSignUpDTO.getCbatchName());
			List<ExaminationBatchDO> certificationBatchDOS = examinationBatchService.selectList(cbatWrapper);
			String str = "";
			for (ExaminationBatchDO certificationBatchDO : certificationBatchDOS) {
				str = str + certificationBatchDO.getId() + ",";
			}
			wrapper.and();
			if (org.apache.commons.lang3.StringUtils.isNotBlank(str)) {
				wrapper.in("cbatch_id", str.substring(0, str.length() - 1));
			} else {
				wrapper.eq("cbatch_id", null);
			}
		}

		//查询用户角色
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			Object orgId = req.getSession().getAttribute("orgId");
			if (orgId != null) {
				wrapper.eq("org_id", orgId);
			} else {
				wrapper.eq("org_id", this.getUser().getOrgId());
			}
		} else {
			if (stuSignUpDTO.getOrgId() != null) {
				wrapper.eq("org_id", stuSignUpDTO.getOrgId());
			}
		}

		Page<StuSignUpDO> page = stuSignUpService.selectPage(getPage(StuSignUpDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			StuSignUpDO obj = (StuSignUpDO) page.getRecords().get(i);
			if (obj.getCheckerId() != null) {
				UserDO userDO = userService.selectById(obj.getCheckerId());
				if (userDO != null) {
					obj.setCheckerName(userDO.getUsername());
				}
			}
			if (obj.getUserId() != null) {
				UserDO userDO = userService.selectById(obj.getUserId());
				if (userDO != null) {
					obj.setUserName(userDO.getUsername());
				}
			}
			if (obj.getCbatchId() != null) {

				//认证批次修改为考试批次
				ExaminationBatchDO examinationBatchDO = examinationBatchService.selectById(obj.getCbatchId());
				if (examinationBatchDO != null) {
					//考试批次名称
					obj.setCbatchName(examinationBatchDO.getName());
				}
			}
			if (obj.getOrgId() != null) {
				OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
				if (organizationNewsDO != null) {
					obj.setOrgName(organizationNewsDO.getName());
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
		return Result.ok(page);
	}

	@Log("获取考场信息")
	@ResponseBody
	@GetMapping("/roomLists")
	public Result<?> dicLists(Long ebatchId) {
		//有数据，则为查二级栏目信息；没数据，则为查一级栏目信息
		List<String> eroomIds = new ArrayList<String>();
		if(userRoleService.listRoleId(getUserId()).indexOf(1l)!=-1) {
			eroomIds = stuSignUpService.selEroomId(examinationBatchService.selectById(ebatchId).getCbatchId().toString(),null);
		}else {
			eroomIds = stuSignUpService.selEroomId(examinationBatchService.selectById(ebatchId).getCbatchId().toString(),getUser().getOrgId().toString());
		}
		List<ExaminationRoomDO> maps = new ArrayList<ExaminationRoomDO>();
		for(String eroomId : eroomIds) {
			maps.add(examinationRoomService.selectById(eroomId));
		}
		return Result.ok(maps);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:stuSignUp:add")
	String add(Model model) {
		model.addAttribute("certificationBatch", certificationBatchService.selTimeAll());
		model.addAttribute("organizationNews", organizationNewsService.selByOrgId());
		model.addAttribute("examinationRoom", examinationRoomService.selByNameId());
		return "jzweb/stuSignUp/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:stuSignUp:edit")
	String edit(@PathVariable("id") Long id, Model model) {
		model.addAttribute("certificationBatch", certificationBatchService.selTimeAll());
		model.addAttribute("organizationNews", organizationNewsService.selByOrgId());
		model.addAttribute("examinationRoom", examinationRoomService.selByNameId());
		StuSignUpDO stuSignUp = stuSignUpService.selectById(id);
		model.addAttribute("stuSignUp", stuSignUp);
		return "jzweb/stuSignUp/edit";
	}

	@GetMapping("/info/{id}")
	@RequiresPermissions("jzweb:stuSignUp:stuSignUp")
	String info(@PathVariable("id") Long id, Model model) {
		StuSignUpDO stuSignUpDO = stuSignUpService.selectById(id);
		if (stuSignUpDO != null) {
			if (stuSignUpDO.getUserId() != null) {
				UserDO userDO = userService.selectById(stuSignUpDO.getUserId());
				if (userDO != null) {
					stuSignUpDO.setUserName(userDO.getUsername());
				}
			}
			if (stuSignUpDO.getCheckerId() != null) {
				UserDO userDO = userService.selectById(stuSignUpDO.getCheckerId());
				if (userDO != null) {
					stuSignUpDO.setCheckerName(userDO.getUsername());
				}
			}
			if (stuSignUpDO.getCbatchId() != null) {
				CertificationBatchDO examinationBatchDO = certificationBatchService.selectById(stuSignUpDO.getCbatchId());
				if (examinationBatchDO != null) {
					stuSignUpDO.setCbatchName(examinationBatchDO.getName());
				}
			}
			if (stuSignUpDO.getOrgId() != null) {
				OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(stuSignUpDO.getOrgId());
				if (organizationNewsDO != null) {
					stuSignUpDO.setOrgName(organizationNewsDO.getName());
				}
			}
		}
		model.addAttribute("stuSignUpDO", stuSignUpDO);
		return "jzweb/stuSignUp/info";
	}

	@Log("跳转考生分配--认证批次信息")
	@GetMapping("/distributionFirst")
	@RequiresPermissions("jzweb:stuSignUp:review")
	String distributionFirst(Model model) {
		Map<String, String> map = new HashMap<>();
		map.put("name", "考生分配天数");
		map.put("type", "candidate_allocation_day");
		String values = dictService.selDicBy(map);
		//todo 2020-03-27,kl,
		// 这里是一个跳转页面的方法，所以没办法报错误；但这里需要判断考生分配功能的延迟天数是否为数字；
		// 如为空或不为数字，默认延迟10天；
		List<Map<Object, Object>> maps;

		if (StringUtils.isBlank(values)) {
			maps = certificationBatchService.selTimeAllSecond(10);
		} else {
			//判断是否为数字;
			//todo 如果设置的为负数，则判断为不是数字；这里考虑是否需要更改；kl-2020-03-30
			boolean b = IdCardUtil.isNumeric(values);
			if (b) {
				maps = certificationBatchService.selTimeAllSecond(Integer.parseInt(values));
			} else {
				maps = certificationBatchService.selTimeAllSecond(10);
			}
		}

		model.addAttribute("certificationBatch", maps);
		return "jzweb/stuSignUp/distribution";
	}

	@Log("跳转考生分配--考点信息")
	@ResponseBody
	@GetMapping("/distributionOrgId")
	public Result<?> distributionOrgId(String cbatchId, String name) {
		if (StringUtils.isNotBlank(cbatchId)) {
			List<Map<Object, Object>> mapsre = new ArrayList<>();
			//查询认证批次信息
			CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(Long.parseLong(cbatchId));

			List<Map<Object, Object>> maps = organizationNewsService.selCerOrg(certificationBatchDO.getProfileId().toString(), name);
			if (maps != null && maps.size() > 0) {
				for (int i = 0; i < maps.size(); i++) {
					//获取目前该考点该次认证批次的考生数
					Map map = new HashMap();
					map.put("orgId", maps.get(i).get("id"));
					map.put("cbatchId", Long.parseLong(cbatchId));
					int stuMaxNum = stuSignUpService.selMaxNum(map);
					int stus = 40;

					Map<String, String> mapstus = new HashMap<>();
					mapstus.put("name", "考场人数");
					mapstus.put("type", "room_number_stu");
					String values = dictService.selDicBy(mapstus);
					if (StringUtils.isNotBlank(values)) {
						//判断是否为数字
						if (IdCardUtil.isNumeric(values)) {
							stus = Integer.parseInt(values);
						}
					}

					//判断该考点的容量（考场数）
					map.clear();
					map.put("orgId", maps.get(i).get("id"));
					map.put("profileId", certificationBatchDO.getProfileId());
					List<ExaminationRoomDO> examinationRoomDOs = examinationRoomService.selByLikeEntity(map);
					if (examinationRoomDOs != null && examinationRoomDOs.size() > 0) {
						//考点容量小于这次导入的信息时，不返回展示
						if ((examinationRoomDOs.size() * stus) < stuMaxNum) {
							maps.get(i).put("num", 0);
						} else {
							maps.get(i).put("num", (examinationRoomDOs.size() * stus) - stuMaxNum);
							mapsre.add(maps.get(i));
						}
					} else {
						maps.get(i).put("num", 0);
					}
				}
			}
			return Result.ok(mapsre);
		}
		return Result.fail("请先选择认证批次！");
	}

	@Log("跳转考生分配--学生信息")
	@ResponseBody
	@GetMapping("/distributionSecond")
	public Result<?> distributionSecond(String pageNumber, String pageSize, String cbatchId) {
		if (StringUtils.isNotBlank(cbatchId)) {
			Page<NoDisStuListVo> page = stuSignUpService.selNoDisStu(Integer.parseInt(pageNumber), Integer.parseInt(pageSize), Long.parseLong(cbatchId));
			return Result.ok(page);
		}
		return Result.fail("请先选择认证批次！");
	}


	@Log("保存考生分配信息")
	@ResponseBody
	@PostMapping("/distributionSave")
	@RequiresPermissions("jzweb:stuSignUp:review")
	public Result<String> distributionSave(String cbatchId, String orgId, String name) {
		//第一步，判断传递参数，准备全体信息
		if (StringUtils.isBlank(cbatchId)) {
			return Result.fail("未选认证批次！");
		}
		if (StringUtils.isBlank(orgId)) {
			return Result.fail("未选考点！");
		}
		if (StringUtils.isBlank(name)) {
			return Result.fail("未选分配考生！");
		}

		String[] userIds = name.split(",");
		OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(Long.parseLong(orgId));

		//第二步--判断该认证批次是否已经建立了理论考试批次；
		//todo 目前定义为只要是认证批次，就一定存在理论考试
		List<ExaminationBatchDO> examinationBatchDO = examinationBatchService.findByKv("cbatch_id", Long.parseLong(cbatchId), "type", 0);
//		if (examinationBatchDO == null || examinationBatchDO.size() < 1) {
//			return Result.fail("该认证批次还未建立理论考试的考试批次，无法导入信息！");
//		} else if (examinationBatchDO.size() > 1) {
//			return Result.fail("该认证批次理论考试为两次，请先核对信息！");
//		}

		//第三步--获取目前该考点该次认证批次的考生数
		Map maps = new HashMap();
		maps.put("orgId", Long.parseLong(orgId));
		maps.put("cbatchId", Long.parseLong(cbatchId));
		int stuMaxNum = stuSignUpService.selMaxNum(maps);
		int stus = 40;

		Map<String, String> mapstus = new HashMap<>();
		mapstus.put("name", "考场人数");
		mapstus.put("type", "room_number_stu");
		String values = dictService.selDicBy(mapstus);
		if (StringUtils.isNotBlank(values)) {
			//判断是否为数字
			if (IdCardUtil.isNumeric(values)) {
				stus = Integer.parseInt(values);
			}
		}

		int a = (stuMaxNum / stus) + 1;//目前能用的考场编号
		int b = 1;

		//如果当前考试数能被整除
		if (stuMaxNum % stus != 0) {
			b = stuMaxNum % stus + 1;//目前已存在考生在考场中的数量
		}

		//第四步--查询认证批次信息
		CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(Long.parseLong(cbatchId));
		List<ExaminationAllocationDO> examinationAllocationDOS = new ArrayList<>();

		//第五步--判断该考点的容量（考场数）
		Map map = new HashMap();
		map.put("orgId", Long.parseLong(orgId));
		map.put("profileId", certificationBatchDO.getProfileId());
		List<ExaminationRoomDO> examinationRoomDOs = examinationRoomService.selByLikeEntity(map);
		if (examinationRoomDOs != null && examinationRoomDOs.size() > 0) {
			//考点容量小于这次导入的信息时，直接返回导入失败
			if ((examinationRoomDOs.size() * stus) < userIds.length + stuMaxNum) {
				return Result.fail("考点目前只能容纳" + ((examinationRoomDOs.size() * stus) - stuMaxNum) + "的考生，请添加考场后导入！");
			}

			//查询该考点该考试批次的最大考试编号
			Map map1 = new HashMap();
			map1.put("orgId", Long.parseLong(orgId));
			map1.put("ebatchId", examinationBatchDO.get(0).getId());
			int cc = examinationAllocationService.selMaxNum(map1);
			//判断该考点该考试批次中该考点是否已安排，如没分配新增信息
			for (int i = 0; i < examinationRoomDOs.size(); i++) {
				ExaminationAllocationDO examinationAllocationDO1 = examinationAllocationService
						.findOneByKv("org_id", Long.parseLong(orgId), "ebatch_id", examinationBatchDO.get(0).getId(), "eroom_id", examinationRoomDOs.get(i).getId());
				if (examinationAllocationDO1 == null) {
					ExaminationAllocationDO examinationAllocationDO = new ExaminationAllocationDO();
					examinationAllocationDO.setEbatchId(examinationBatchDO.get(0).getId());//考试批次id
					examinationAllocationDO.setOrgId(Long.parseLong(orgId));//机构id
					//转成01格式
					String ccs = WithZoreUtil.frontCompWithZore(cc + i + 1, 2);
					examinationAllocationDO.setRoomNumber(ccs);//考场编号
					examinationAllocationDO.setEroomId(examinationRoomDOs.get(i).getId());//考场id
					examinationAllocationDO.setCreaterId(this.getUserId());//创建人
					examinationAllocationDO.setCreaterDate(new Date());//创建时间
					examinationAllocationService.insert(examinationAllocationDO);
					examinationAllocationDOS.add(examinationAllocationDO);
				} else {
					examinationAllocationDOS.add(examinationAllocationDO1);
				}
			}
		} else {
			return Result.fail("考点目前没有考场，请添加考场后导入！");
		}

		//第六步--根据机构id和考试批次中的理论考试id判断该认证批次是否已存在考点分配信息
		ExaminationPointDO examinationPointDO = examinationPointService
				.findOneByKv("ebatch_id", examinationBatchDO.get(0).getId(), "org_id", organizationNewsDO.getId());
		if (examinationPointDO == null) {
			ExaminationPointDO examinationPointDO1 = new ExaminationPointDO();
			examinationPointDO1.setEbatchId(examinationBatchDO.get(0).getId());//考试批次id
			examinationPointDO1.setOrgId(organizationNewsDO.getId());//机构id
			examinationPointDO1.setUserId(organizationNewsDO.getLeadingCadreId());//负责人id
			examinationPointDO1.setName(organizationNewsDO.getName());//考点名称
			examinationPointDO1.setCreaterId(this.getUserId());//创建人
			examinationPointDO1.setCreaterDate(new Date());//创建时间
			examinationPointService.insert(examinationPointDO1);
		}

		//第七步--查询证书信息，并配置考号部分数据
		CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(certificationBatchDO.getNewsId());
		if (certificateNewsDO == null) {
			return Result.fail("该认证批次关联的证书信息有误，请联系管理员！");
		}

		//1.证书等级代码
		String cerNum;
		if (certificateNewsDO.getGrade().equals(0)) {
			cerNum = "30";
		} else if (certificateNewsDO.getGrade().equals(1)) {
			cerNum = "20";
		} else {
			cerNum = "10";
		}

		//2.获取当前年份后两位
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		String year = format.format(date);
		String yearRe = year.substring(year.length() - 2);

		boolean rec = true;
		for (int j = 0; j < userIds.length; j++) {
			StuSignUpDO stuSignUpDO = stuSignUpService.selectById(userIds[j]);
			if (stuSignUpDO != null) {
				stuSignUpDO.setOrgId(Long.parseLong(orgId));//考点id(机构id)
				stuSignUpDO.setOrgNum(organizationNewsDO.getOrgNum());//考点编号

				//判断考场容量和当前考生数的大小，是否需要新增考场
				if ((j + stuMaxNum) > (a * stus)) {
					a = a + 1;
				}

				//单数字转成01格式
				String ccs = WithZoreUtil.frontCompWithZore(a, 2);
				stuSignUpDO.setEallocationNum(ccs);//考场编号
				for (ExaminationAllocationDO examinationAllocationDO : examinationAllocationDOS) {
					if (examinationAllocationDO.getRoomNumber().equals(ccs)) {
						stuSignUpDO.setEallocationId(examinationAllocationDO.getId());//考场id
					}
				}

				int stuNum;

				if (((j + b) % stus) == 0) {
					stuNum = stus;
				} else {
					stuNum = (j + b) % stus;
				}

				//考生座位顺序号，单数字转成01格式
				String ssNum = WithZoreUtil.frontCompWithZore(stuNum, 2);

				//考生编号格式：职业技能等级标准代码（3位） +证书等级代码（2位）+年份（2位）+考点序列号（3位）+考场号（2位）+座位号（2位）
				String ticketNum = "690" + cerNum + yearRe + organizationNewsDO.getOrgNum() + ccs + ssNum;
				stuSignUpDO.setTicketNumber(ticketNum);//考号
				stuSignUpDO.setState(3);//状态改为已分配
				boolean cc = stuSignUpService.updateById(stuSignUpDO);
				if (!cc) {
					if (rec == true) {
						rec = cc;
					}
				}
			} else {
				return Result.fail("未查到考生信息！请稍后重试");
			}
		}

		if (rec) {
			ExaminationBatchDO examinationBatchDOs = examinationBatchService.findOneByKv("cbatch_id", Long.parseLong(cbatchId), "type", 1);
			if (examinationBatchDOs != null) {
				TestPaperTemplateDO testPaperTemplateDO = testPaperTemplateService.findOneByKv("type", 1, "news_id", certificateNewsDO.getId());
				if (testPaperTemplateDO != null) {
					//调用一下考生分组类
					String ccdd = stuGroup(1, testPaperTemplateDO.getId(), examinationBatchDOs.getId(), certificationBatchDO.getId(), certificationBatchDO.getProfileId());
					if (!ccdd.equals("成功")) {
						return Result.fail(ccdd);
					} else {
						return Result.ok("分配成功，且已完成所有考生的技能考试分组！");
					}
				}
			}

			return Result.ok("分配成功");
		} else {
			return Result.fail();
		}
	}

	@Log("页面导航信息树")
	@GetMapping("/tree")
	@ResponseBody
	public Tree<Map> tree() {
		Tree<Map> tree = organizationNewsService.selOrgList();
		return tree;
	}


	@Log("添加考生报名")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:stuSignUp:add")
	public Result<String> save(StuSignUpDO stuSignUp) {
		stuSignUpService.insert(stuSignUp);
		return Result.ok();
	}

	@Log("修改考生报名")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:stuSignUp:edit")
	public Result<String> update(StuSignUpDO stuSignUp) {
		boolean update = stuSignUpService.updateById(stuSignUp);
		return update ? Result.ok() : Result.fail();
	}

	@Log("删除考生报名")
	@PostMapping("/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUp:remove")
	public Result<String> remove(Long id) {
		stuSignUpService.deleteById(id);
		return Result.ok();
	}

	@Log("批量删除考生报名")
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUp:batchRemove")
	public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
		stuSignUpService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}
	
	@Log("考生重考报名")
	@PostMapping("/reExam")
	@ResponseBody
	@RequiresPermissions("jzwb:stuSignUp:reExam")
	public Result<String> reExam(Long id) {
		StuSignUpDO s = stuSignUpService.selectById(id);
		s.setState(8);//将考试转态“已考完”更改为“考试中”
		stuSignUpService.updateById(s);
		Map map = new HashMap<String,String>();
		map.put("stu_sign_id", id);
		examinationAnswerSheetService.deleteByMap(map);
		return Result.ok("操作成功！");
	}

	@Log("审核")
	@PostMapping("/review")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUp:review")
	public Result<String> review(@RequestParam("ids[]") Long[] ids, Integer state, String remark) {
		if (state.equals(2) || state.equals(1)) {

			//查询字典:消息模板
			DictDO dic = null;
			String valStr = "";
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (state == 2) {
				dic = dictService.findOneByKv("type", "check_no_pass");
				valStr = dic.getValue().replace("{value4}", remark);
			} else {
				dic = dictService.findOneByKv("type", "check_pass");
				valStr = dic.getValue();
			}
			valStr = valStr.replace("{value1}", "报名信息");
			valStr = valStr.replace("{value2}", this.getUser().getUsername());
			valStr = valStr.replace("{value3}", formatter.format(new Date()));


			int i = 0;
			for (Long id : ids) {
				StuSignUpDO stuSignUpDO = stuSignUpService.selectById(id);
				if (stuSignUpDO != null) {
					if(stuSignUpDO.getState().equals(0)){
						stuSignUpDO.setState(state);
						List<StuSignUpDO> stuSignUpDOs = stuSignUpService.findByKv("user_id", stuSignUpDO.getUserId());
						if (stuSignUpDOs != null && stuSignUpDOs.size() > 0) {
							CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(stuSignUpDO.getCbatchId());
							if (certificationBatchDO != null) {
								for (StuSignUpDO stuSignUpDO1 : stuSignUpDOs) {
									//如果在该证书等级的考试中，考生状态存在已过理论，且时间为一年内，则直接定义为待分配状态
									if (stuSignUpDO1.getState().equals(6)) {
										CertificationBatchDO certificationBatchDO1 = certificationBatchService.selectById(stuSignUpDO1.getCbatchId());
										if (certificationBatchDO1 != null) {
											if (certificationBatchDO1.getNewsId().equals(certificationBatchDO.getNewsId())) {
												ExaminationBatchDO examinationBatchDO = examinationBatchService.findOneByKv("cbatch_id", certificationBatchDO1.getId(), "type", 0);
												if (examinationBatchDO != null) {
													long diff = (new Date()).getTime() - examinationBatchDO.getStartTime().getTime();//这样得到的差值是毫秒级别
													long days = diff / (1000 * 60 * 60 * 24);
//                                                long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
//                                                long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
//                                                System.out.println(""+days+"天"+hours+"小时"+minutes+"分");
													if (days <= 365) {
														stuSignUpDO.setState(5);
													}
												}
											}
										}

									}
								}
							}
						}

						MsgDO msg = new MsgDO();
						stuSignUpDO.setCheckerId(this.getUserId());
						stuSignUpDO.setCheckerDate(new Date());
						if (state.equals(2)) {
							stuSignUpDO.setRemark(remark);//未通过，添加备注
							msg.setTitle("报名信息审核未通过！");
						} else {
							msg.setTitle("报名信息审核已通过！");
							stuSignUpDO.setRemark("");//审核通过，清空备注
						}
						boolean b = stuSignUpService.updateById(stuSignUpDO);
						if (b) {

							msg.setContent(valStr);
							msg.setUserId(stuSignUpDO.getUserId());
							msg.setCreaterDate(new Date());
//						msg.setEnclosure();
							msg.setType(0);
							msg.setMsgType(0);
							msg.setState(0);
							msg.setCreaterId(this.getUserId());
							msgService.insert(msg);

							//------------------------订阅消息模块-----------------------------\
							UserDO user = userService.selectById(stuSignUpDO.getUserId());
							MsgTemplateDO msgTemplate = msgTemplateService.findOneByKv("type", 0, "temp_ip", 101);
							if (user.getCerOpenId() != null) {
								if (msgTemplate != null) {
									String[] value = null;
									if (state == 1) {//通过
										MsgTemplateDO templateDO = msgTemplateService.findOneByKv("pid", msgTemplate.getId(), "type", 2, "temp_ip", 101);
										value = templateDO.getContent().split("/n");
										for (int a = 0; a < value.length; a++) {
											value[a] = value[a].replace("{value1}", "报名");
											value[a] = value[a].replace("{value2}", "报名");
											value[a] = value[a].replace("{date}", formatter.format(new Date()));
										}
									} else if (state == 2) {//未通过
										MsgTemplateDO templateDO = msgTemplateService.findOneByKv("pid", msgTemplate.getId(), "type", 3, "temp_ip", 101);
										value = templateDO.getContent().split("/n");
										for (int a = 0; a < value.length; a++) {
											value[a] = value[a].replace("{value1}", "报名");
											value[a] = value[a].replace("{value2}", "报名");
											value[a] = value[a].replace("{remark}", remark);
											value[a] = value[a].replace("{date}", formatter.format(new Date()));
										}
									}
									String[] parm = msgTemplate.getContent().split(",");
									Map<String, TemplateData> map = PackTemplateMap.get1(value, parm);

									MpConfigDO mc = mpConfigService.selectById(101);
									//发送订阅消息
									wxPushServiceQcl.sendMsgToUser(mc.getId().intValue(), user.getCerOpenId(), msgTemplate.getCode(), map, "pages/userSign/userSign");
								}
							}
							//------------------------订阅消息模块结束-----------------------------\

							i++;
						} else {
							break;
						}

					}
				}
			}
			if (i == ids.length) {
				return Result.build(0, "已成功审核：" + i + "条数据");
			} else {
				return Result.fail("审核状态修改失败！");
			}
		} else {
			return Result.fail("审核状态修改失败！");
		}
	}


	/**
	 * 下载导入模板
	 *
	 * @param response
	 */
	@RequestMapping("/downloadImportTemplate")
	@RequiresPermissions("jzweb:stuSignUp:import")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response) {
		List<StuSignUpVo> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "考生报名信息导入模板", "考生报名信息导入模板", StuSignUpVo.class, "考生报名信息导入模板", response);
	}

	/**
	 * 考生信息导入
	 *
	 * @param file excel文件
	 */
	@Log("考生信息导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:stuSignUp:import")
	public Result<?> importExcel(HttpServletRequest req, @RequestParam("file") MultipartFile file, String cbatchId,String orgId) {
		if(orgId.equals("")) {
			return Result.fail("请再左侧选择考点！");
		}
		//---------------------------------检测导入信息及条件-----------------------------------------
		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		//第二步--解析文件获得数据
		List<StuSignUpVo> list = EasyPoiUtil.importExcel(file, 1, 1, StuSignUpVo.class);
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}

		//第三步--判断导入人员身份，获取导入人员信息
		OrganizationNewsDO organizationNewsDOss=organizationNewsService.selectById(orgId);
		if (organizationNewsDOss == null) {
			return Result.fail("该机构信息错误，无法导入信息！");
		} 
		OrganizationRolesDO organizationRolesDOs = organizationRolesService.findOneByKv("org_id", orgId, "role_type", 5);
		if (organizationRolesDOs == null) {
			return Result.fail("该机构不具备考核站点角色，无法导入信息！");
		}
//		//todo 超级管理员是否需要判断导入信息
//		if (this.getUser().getOrgId() != null) {
//			OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(this.getUser().getOrgId());
//			if (organizationNewsDO == null) {
//				return Result.fail("您的所属机构信息错误，无法导入信息！");
//			} else {
//
//				Object orgId = req.getSession().getAttribute("orgId");
//				if (orgId != null) {
//					OrganizationRolesDO organizationRolesDOs = organizationRolesService.findOneByKv("org_id", orgId1, "role_type", 5);
//					if (organizationRolesDOs == null) {
//						return Result.fail("您的所属机构不具备考核站点角色，无法导入信息！");
//					}
//				} else {
//					OrganizationRolesDO organizationRolesDOs = organizationRolesService.findOneByKv("org_id", this.getUser().getOrgId(), "role_type", 5);
//					if (organizationRolesDOs == null) {
//						return Result.fail("您的所属机构不具备考核站点角色，无法导入信息！");
//					}
//				}
//
//				organizationNewsDOss = organizationNewsDO;
//			}
//		} else {
//			return Result.fail("您的所属机构信息错误，无法导入信息！");
//		}

		//第四步--判断该认证批次是否已经建立了理论考试批次；
		//todo 目前定义为只要是认证批次，就一定存在理论考试
		List<ExaminationBatchDO> examinationBatchDO = examinationBatchService.findByKv("id", Long.parseLong(cbatchId), "type", 0);
//		if (examinationBatchDO == null || examinationBatchDO.size() < 1) {
//			return Result.fail("该认证批次还未建立理论考试的考试批次，无法导入信息！");
//		} else if (examinationBatchDO.size() > 1) {
//			return Result.fail("该认证批次理论考试为两次，请先核对信息！");
//		}

		//第五步--获取目前该考点该次认证批次的考生数
//		Map maps = new HashMap();
//		maps.put("orgId", organizationNewsDOss.getId());
//		maps.put("cbatchId", Long.parseLong(cbatchId));
//		int stuMaxNum = stuSignUpService.selMaxNum(maps);
//		int stus = 40;
//
//		Map<String, String> mapstus = new HashMap<>();
//		mapstus.put("name", "考场人数");
//		mapstus.put("type", "room_number_stu");
//		String values = dictService.selDicBy(mapstus);
//		if (StringUtils.isNotBlank(values)) {
//			//判断是否为数字
//			if (IdCardUtil.isNumeric(values)) {
//				stus = Integer.parseInt(values);
//			}
//		}
//		int a = (stuMaxNum / stus) + 1;//目前能用的考场编号
//		int b = 1;
//
//		//如果当前考试数能被整除
//		if (stuMaxNum % stus != 0) {
//			b = stuMaxNum % stus + 1;//目前已存在考生在考场中的数量
//		}

		//第六步--查询认证批次信息
		CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(Long.parseLong(cbatchId));

		List<ExaminationAllocationDO> examinationAllocationDOS = new ArrayList<>();

//		//第七步--判断该考点的容量（考场数）
//		Map map = new HashMap();
//		map.put("orgId", organizationNewsDOss.getId());
//		map.put("profileId", certificationBatchDO.getProfileId().toString());
//		List<ExaminationRoomDO> examinationRoomDOs = examinationRoomService.selByLikeEntity(map);
//		if (examinationRoomDOs != null && examinationRoomDOs.size() > 0) {
//			//考点容量小于这次导入的信息时，直接返回导入失败
//			if ((examinationRoomDOs.size() * stus) < list.size() + stuMaxNum) {
//				return Result.fail("考点目前只能容纳" + ((examinationRoomDOs.size() * stus) - stuMaxNum) + "的考生，请添加考场后导入！");
//			}
//
//			//查询该考点该考试批次的最大考试编号
//			Map map1 = new HashMap();
//			map1.put("orgId", organizationNewsDOss.getId());
//			map1.put("ebatchId", examinationBatchDO.get(0).getId());
//			int cc = examinationAllocationService.selMaxNum(map1);
//			//判断该考点该考试批次中该考点是否已安排，如没分配新增信息
//			for (int i = 0; i < examinationRoomDOs.size(); i++) {
//				ExaminationAllocationDO examinationAllocationDO1 = examinationAllocationService
//						.findOneByKv("org_id", organizationNewsDOss.getId(), "ebatch_id", examinationBatchDO.get(0).getId(), "eroom_id", examinationRoomDOs.get(i).getId());
//				if (examinationAllocationDO1 == null) {
//					ExaminationAllocationDO examinationAllocationDO = new ExaminationAllocationDO();
//					examinationAllocationDO.setEbatchId(examinationBatchDO.get(0).getId());//考试批次id
//					examinationAllocationDO.setOrgId(organizationNewsDOss.getId());//机构id
//					//转成01格式
//					String ccs = WithZoreUtil.frontCompWithZore(cc + i + 1, 2);
//					examinationAllocationDO.setRoomNumber(ccs);//考场编号
//					examinationAllocationDO.setEroomId(examinationRoomDOs.get(i).getId());//考场id
//					examinationAllocationDO.setCreaterId(this.getUserId());//创建人
//					examinationAllocationDO.setCreaterDate(new Date());//创建时间
//					examinationAllocationService.insert(examinationAllocationDO);
//					examinationAllocationDOS.add(examinationAllocationDO);
//				} else {
//					examinationAllocationDOS.add(examinationAllocationDO1);
//				}
//			}
//		} else {
//			return Result.fail("考点目前没有考场，请添加考场后导入！");
//		}

		//第八步--根据机构id和考试批次中的理论考试id判断该认证批次是否已存在考点分配信息
		ExaminationPointDO examinationPointDO = examinationPointService
				.findOneByKv("ebatch_id", examinationBatchDO.get(0).getId(), "org_id", organizationNewsDOss.getId());
		if (examinationPointDO == null) {
			ExaminationPointDO examinationPointDO1 = new ExaminationPointDO();
			examinationPointDO1.setEbatchId(examinationBatchDO.get(0).getId());//考试批次id
			examinationPointDO1.setOrgId(organizationNewsDOss.getId());//机构id
			examinationPointDO1.setUserId(organizationNewsDOss.getLeadingCadreId());//负责人id
			examinationPointDO1.setName(organizationNewsDOss.getName());//考点名称
			examinationPointDO1.setCreaterId(this.getUserId());//创建人
			examinationPointDO1.setCreaterDate(new Date());//创建时间
			examinationPointService.insert(examinationPointDO1);
		}

//		//第九步--查询证书信息，并配置考号部分数据
//		CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(certificationBatchDO.getNewsId());
//		if (certificateNewsDO == null) {
//			return Result.fail("该认证批次关联的证书信息有误，请联系管理员！");
//		}

		//1.证书等级代码
//		String cerNum;
//		if (certificateNewsDO.getGrade().equals(0)) {
//			cerNum = "30";
//		} else if (certificateNewsDO.getGrade().equals(1)) {
//			cerNum = "20";
//		} else {
//			cerNum = "10";
//		}

		//2.获取当前年份后两位
//		Date date = new Date();
//		SimpleDateFormat format = new SimpleDateFormat("yyyy");
//		String year = format.format(date);
//		String yearRe = year.substring(year.length() - 2);
//
//		FileUtil fileUtil = new FileUtil();

		//---------------------------------验证数据并导入-----------------------------------------
		//数据该市行为第三行，第一行标题，第二行表头
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<StuSignUpDO> upDOList = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			UserDO rrUserDo = null;
			UserDO rsUserDo = null;
			StringBuilder sb = new StringBuilder();
			//第一步验证是否存在空值
			if (StringUtils.isBlank(list.get(i).getName())) {
				sb.append("第" + (i + startRow) + "行姓名未填写，请完善！" + ";");
			} else {
//				if (StringUtils.isBlank(list.get(i).getSex())) {
//					sb.append("第" + (i + startRow) + "行性别未填写，请完善！" + ";");
//				} else {
					if (StringUtils.isBlank(list.get(i).getTicketNumber())) {
						sb.append("第" + (i + startRow) + "行准考证号未填写，请完善！" + ";");
					} else {
						if(StringUtils.isBlank(list.get(i).getEallocationName())) {
							sb.append("第" + (i + startRow) + "行考场名称未填写，请完善！" + ";");
						}else {
							if (StringUtils.isBlank(list.get(i).getIdNumber())) {
								sb.append("第" + (i + startRow) + "行考生编号未填写，请完善！" + ";");
							} else {
//							if (StringUtils.isBlank(list.get(i).getImageUrl())) {
//								sb.append("第" + (i + startRow) + "行考生寸照未填入或不在单元格内，请完善！" + ";");
//							} else {
//								if (!FilesSizeUtil.imgJudge(list.get(i).getImageUrl())) {
//									sb.append("第" + (i + startRow) + "行考生寸照格式错误，请插入像素为295*413且大小不超过1M（一兆）的一寸照！" + ";");
//								} else {
									//第二步验证电话号码
//									if (!ValidUtils.isMobile(list.get(i).getMobile())) {
//										sb.append("第" + (i + startRow) + "行手机号码格式错误，请完善！" + ";");
//									} else {
//										//第三步验证身份证号码
//										if (!ValidUtils.isIDCard(list.get(i).getIdNumber())) {
//											sb.append("第" + (i + startRow) + "行身份证号码格式错误，请完善！" + ";");
//										} else {
											//判断身份证中性别信息和导入性别是否一致
//											String sexNum = list.get(i).getIdNumber().substring(list.get(i).getIdNumber().length() - 2, list.get(i).getIdNumber().length() - 1);
//											int jj = Integer.parseInt(sexNum) & 1;
//											if (list.get(i).getSex().equals("男")) {
//												if (jj != 1) {
//													sb.append("第" + (i + startRow) + "行输入性别和身份证性别信息有出入，请检查！" + ";");
//												}
//											} else if (list.get(i).getSex().equals("女")) {
//												if (jj != 0) {
//													sb.append("第" + (i + startRow) + "行输入性别和身份证性别信息有出入，请检查！" + ";");
//												}
//											} else {
//												sb.append("第" + (i + startRow) + "行性别错误，请填写：男或女！" + ";");
//											}

											if (sb.length() == 0) {
												//第四步排重验证（自身比较）
												for (int j = 0; j < list.size(); j++) {
													if (i != j) {
														if (list.get(i).getTicketNumber().equals(list.get(j).getTicketNumber())) {
															sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行准考证号重复，重复值：" + list.get(i).getIdNumber() + ";");
														}
													}
												}

												//转换一下图片路径，将反斜杠替换掉
												//String url = list.get(i).getImageUrl().replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
												//String imgUrl = url.replace("\\", "/");


												//第五步根据手机号码获取用户信息并判断，如没有则新建，如果则返回信息
//												UserDO userDO = userService.findOneByKv("mobile", list.get(i).getMobile());
//												if (userDO != null) {
//													userDO.setHeadPortrait(imgUrl);
//													if (userDO.getName() != null) {
//														if (!userDO.getName().equals(list.get(i).getName())) {
//															sb.append("第" + (i + startRow) + "行考生已注册，但姓名不一致，请修改后重试！" + ";");
//														}
//													} else {
//														userDO.setName(list.get(i).getName());
//													}
//													if (userDO.getIdNumber() != null) {
//														if (!userDO.getIdNumber().equals(list.get(i).getIdNumber())) {
//															sb.append("第" + (i + startRow) + "行考生已注册，但身份证号码不一致，请修改后重试！" + ";");
//														}
//													} else {
//														userDO.setIdNumber(list.get(i).getIdNumber());
//													}
//													if (userDO.getSex() != null) {
//														if (list.get(i).getSex().equals("女")) {
//															if (!userDO.getSex().equals(2L)) {
//																sb.append("第" + (i + startRow) + "行考生已注册，但性别不一致，请修改后重试！" + ";");
//															}
//														} else {
//															if (!userDO.getSex().equals(1L)) {
//																sb.append("第" + (i + startRow) + "行考生已注册，但性别不一致，请修改后重试！" + ";");
//															}
//														}
//
//													} else {
//														if (list.get(i).getSex().equals("女")) {
//															userDO.setSex(2L);
//														} else {
//															userDO.setSex(1L);
//														}
//													}
//													userDO.setOrgId(organizationNewsDOss.getId());
//													userDO.setOrgName(organizationNewsDOss.getName());
//													List<Long> roleIds = userRoleService.listRoleId(userDO.getId());
//													if (roleIds != null && roleIds.size() > 0) {
//														userDO.setroleIds(roleIds);
//													} else {
//														List<Long> list11 = new ArrayList<>();
//														list11.add(56L);
//														userDO.setroleIds(list11);
//													}
//
//													userService.updateById(userDO);
//													rsUserDo = userDO;
//												} else {
//													UserDO userDO1 = new UserDO();
//													userDO1.setUsername(list.get(i).getMobile());
//													userDO1.setName(list.get(i).getName());
//													userDO1.setIdNumber(list.get(i).getIdNumber());
//													userDO1.setMobile(list.get(i).getMobile());
//													userDO1.setHeadPortrait(imgUrl);
//
//													//初始密码设为身份证号后六位
//													String password = list.get(i).getIdNumber().substring(list.get(i).getIdNumber().length() - 6);
//													String salt = UUIDUtils.get();
//													String encodePasswd = PasswdUtils.get(password, salt);
//													userDO1.setSalt(salt);
//													userDO1.setPassword(encodePasswd);
//													userDO1.setType(0);//默认个人会员
//													userDO1.setMoney(BigDecimal.valueOf(0.0));//默认0元
//													userDO1.setGmtCreate(new Date());
//													userDO1.setGmtModified(userDO1.getGmtCreate());
//													userDO1.setStatus(1);//默认正常
//													if (list.get(i).getSex().equals("男")) {
//														userDO1.setSex(1L);//性别
//													} else {
//														userDO1.setSex(2L);//性别
//													}
//
//
//													userDO1.setOrgId(organizationNewsDOss.getId());
//													userDO1.setOrgName(organizationNewsDOss.getName());
//
//													List<Long> roleIds = userRoleService.listRoleId(userDO1.getId());
//													if (roleIds != null && roleIds.size() > 0) {
//														userDO1.setroleIds(roleIds);
//													} else {
//														List<Long> list11 = new ArrayList<>();
//														list11.add(56L);
//														userDO1.setroleIds(list11);
//													}
//													rrUserDo = userDO1;
//												}

												//第六步排重验证（和数据库比较），根据考生名称、考生身份证号码、该场考试的认证批次判断该考生是否已报名该考试
												StuSignUpDO stuSignUpDO = stuSignUpService.findOneByKv("name", list.get(i).getName(), "id_number", list.get(i).getIdNumber(), "cbatch_id", Long.parseLong(cbatchId));
												if (stuSignUpDO != null) {
													sb.append("第" + (i + startRow) + "行考生已报名该次考试！" + ";");
												}

											}

										//}
									//}
								//}
							//}
							}
						}
					}
				//}
			}


			if (sb.length() > 0) {
				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
				errorCodeVo.setSeq(cout);
				cout += 1;
				errorCodeVo.setErrorCode(sb.toString());
				list1.add(errorCodeVo);
			} else {
				if (rrUserDo != null) {
					boolean cc = userService.insertNoPW(rrUserDo);
					if (!cc) {
						log.info("第" + (i + startRow) + "行考生用户信息导入失败，建议删除重新导入！" + ";");
					}
				}

				//转换一下图片路径，将反斜杠替换掉
				//String url = list.get(i).getImageUrl().replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
				//String imgUrl = url.replace("\\", "/");

				StuSignUpDO stuSignUpDO1 = new StuSignUpDO();
				//stuSignUpDO1.setUserId(list.get(i).getTicketNumber());//准考证号
				stuSignUpDO1.setName(list.get(i).getName());//姓名
				stuSignUpDO1.setIdNumber(list.get(i).getIdNumber());//身份证号码
				stuSignUpDO1.setCbatchId(Long.parseLong(cbatchId));//认证批次id
				stuSignUpDO1.setSignUpTime(new Date());//报名时间
//				if (rsUserDo != null) {
//					stuSignUpDO1.setUserId(rsUserDo.getId());//用户id
//				} else {
//					stuSignUpDO1.setUserId(rrUserDo.getId());//用户id
//				}
				//stuSignUpDO1.setPhoto(imgUrl);//照片
				stuSignUpDO1.setType(0);
				stuSignUpDO1.setState(3);//默认已分配
				stuSignUpDO1.setOrgId(organizationNewsDOss.getId());//考点id(机构id)
				stuSignUpDO1.setOrgNum(organizationNewsDOss.getOrgNum());//考点编号
				
				//获取考场
				ExaminationRoomDO examinationRoom = examinationRoomService.findOneByKv("org_id",organizationNewsDOss.getId(),"name",list.get(i).getEallocationName());
				if(examinationRoom==null) {
					examinationRoom = new ExaminationRoomDO();
					examinationRoom.setOrgId(organizationNewsDOss.getId());
					examinationRoom.setProfileId("1241245212023312386");//统一为：幼儿照护职业技能等级证书
					examinationRoom.setName(list.get(i).getEallocationName());
					examinationRoom.setType(0);//理论考场
					examinationRoom.setSeatSize(100);//座位数，暂时无用，随便设置
					examinationRoom.setCampus("1");//校区，暂时无用，随便设置
					examinationRoom.setStoriedBuilding("1");//楼栋，暂时无用，随便设置
					examinationRoom.setHouseNumber("1");//门牌号，暂时无用，随便设置
					examinationRoom.setCreaterId(getUserId());//创建者ID
					examinationRoom.setState(1);//考场审核状态设置为通过
					examinationRoom.setCheckerId(getUserId());//考场审核人ID
					examinationRoom.setCheckerDate(new Date());//审核时间
					examinationRoomService.insert(examinationRoom);
					examinationRoom = examinationRoomService.findOneByKv("org_id",organizationNewsDOss.getId(),"name",list.get(i).getEallocationName());
				}
				stuSignUpDO1.setEallocationId(examinationRoom.getId());
				stuSignUpDO1.setEallocationNum(examinationRoom.getName());
				
				//判断考场容量和当前考生数的大小，是否需要新增考场
//				if ((i + stuMaxNum) >= (a * stus)) {
//					a = a + 1;
//				}
//
//				//单数字转成01格式
//				String ccs = WithZoreUtil.frontCompWithZore(a, 2);
//				stuSignUpDO1.setEallocationNum(ccs);//考场编号
//				for (ExaminationAllocationDO examinationAllocationDO : examinationAllocationDOS) {
//					if (examinationAllocationDO.getRoomNumber().equals(ccs)) {
//						stuSignUpDO1.setEallocationId(examinationAllocationDO.getId());//考场id
//					}
//				}
//
//				int stuNum;
//
//				if (((i + b) % stus) == 0) {
//					stuNum = stus;
//				} else {
//					stuNum = (i + b) % stus;
//				}

				//考生座位顺序号，单数字转成01格式
				//String ssNum = WithZoreUtil.frontCompWithZore(stuNum, 2);

				//考生编号格式：职业技能等级标准代码（3位） +证书等级代码（2位）+年份（2位）+考点序列号（3位）+考场号（2位）+座位号（2位）
				//String ticketNum = "690" + cerNum + yearRe + organizationNewsDOss.getOrgNum() + ccs + ssNum;
				stuSignUpDO1.setTicketNumber(list.get(i).getTicketNumber());//考号

				stuSignUpDO1.setCheckerId(this.getUserId());//默认审核人为导入者
				stuSignUpDO1.setCheckerDate(new Date());//默认审核时间为导入时间
				upDOList.add(stuSignUpDO1);

			}
		}

		if (list1.size() == 0) {
			boolean c = stuSignUpService.insertBatch(upDOList, upDOList.size());
			if (c) {
				ExaminationBatchDO examinationBatchDOs = examinationBatchService.findOneByKv("cbatch_id", Long.parseLong(cbatchId), "type", 1);
//				if (examinationBatchDOs != null) {
//					TestPaperTemplateDO testPaperTemplateDO = testPaperTemplateService.findOneByKv("type", 1, "news_id", certificateNewsDO.getId());
//					if (testPaperTemplateDO != null) {
//						//调用一下考生分组类
//						String ccdd = stuGroup(1, testPaperTemplateDO.getId(), examinationBatchDOs.getId(), certificationBatchDO.getId(), certificationBatchDO.getProfileId());
//						if (!ccdd.equals("成功")) {
//							return Result.fail(ccdd);
//						} else {
//							return Result.ok("分配成功，且已完成所有考生的技能考试分组！");
//						}
//					}
//				}

				return Result.ok("成功导入" + list.size() + "条数据");
			} else {
				//导入失败，删除已导入的图片
//				for (int fi = 0; fi < list.size(); fi++) {
//					if (list.get(fi).getImageUrl() != null) {
//						String url = list.get(fi).getImageUrl().replace(ValuesUtil.returnUrl, ValuesUtil.localUrl);
//						String imgUrl = url.replace("\\", "/");
//						boolean b1 = fileUtil.DeleteFolder(imgUrl);
//						if (b1) {
//							log.info("考生导入信息失败删除图片第" + (fi + 1) + "张，情况：" + b1);
//						}
//					}
//				}
				return Result.fail("报名信息导入错误，请稍后重试或联系管理员");
			}
		} else {
			//导入失败，删除已导入的图片
//			for (int fi = 0; fi < list.size(); fi++) {
//				if (list.get(fi).getImageUrl() != null) {
//					String url = list.get(fi).getImageUrl().replace(ValuesUtil.returnUrl, ValuesUtil.localUrl);
//					String imgUrl = url.replace("\\", "/");
//					boolean b1 = fileUtil.DeleteFolder(imgUrl);
//					log.info("考生导入信息失败删除图片第" + (fi + 1) + "张，情况：" + b1);
//				}
//			}

			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			//将list1存到缓存中
			EhCacheUtil.put("stuSignUp" + this.getUserId(), jsonArray);
			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}

	}

	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importError")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:stuSignUp:import")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考生报名导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("stuSignUp" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}
}
